﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Brain
{
    public class TerrainWorldObject : WorldObject
    {
        public HeightMap HeightMap;

        public short[] Indices;

        public Triangle[] Triangles;

        public bool WipeCPUContent = false;
        public bool MakeTris = false;

        public override string ModelPlace
        {
            get
            {
                return modelPlace;
            }
            set
            {
                modelPlace = value;
                if (!string.IsNullOrEmpty(value))
                {
                    this.HeightMap = Engine.Instance.ContentManager.Load<HeightMap>(value);
                    Engine.Instance.RenderManager3D.InitializeTerrainDefaultRendering(this, WipeCPUContent, MakeTris);
                }
            }
        }

        public TerrainWorldObject(Texture2D tex, float factor)
        {
            HeightMap = new HeightMap();
            HeightMap.ReadFromTexture(tex, factor);
        }
        public TerrainWorldObject()
        {
            HeightMap = new HeightMap();
        }
        public TerrainWorldObject(string modelPlace, bool makeTris, bool wipeCPU)
        {
            this.WipeCPUContent = wipeCPU;
            this.MakeTris = makeTris;
            this.ModelPlace = modelPlace;
        }

        public void MakeTriangles()
        {
            IRenderManager3D render = Engine.Instance.RenderManager3D;
            if (this.Indices == null)
            {
#if MONOGAME
                throw new Exception("Programmer decided to delete the Index Buffer from the Terrain. Cannot be Get using OpenGL!");
#else

                // REBUILD indices, because user decided to delete it
                BrainModelMesh mesh = (this.Model as BrainModel).Meshes[0];
                this.Indices = new short[mesh.IndexBuffer.IndexCount];
                mesh.IndexBuffer.GetData(this.Indices);
#endif
            }

            Triangles = new Triangle[Indices.Length / 3];

            for (int i = 0; i < Indices.Length - 2; i += 3)
            {
                int index1 = Indices[i];
                int index2 = Indices[i + 1];
                int index3 = Indices[i + 2];

                Vector3 v1 = render.GetTerrainVertex(this, index1);
                Vector3 v2 = render.GetTerrainVertex(this, index2);
                Vector3 v3 = render.GetTerrainVertex(this, index3);

                Triangle triangle = new Triangle();
                triangle.Vertex1 = v1;
                triangle.Vertex2 = v2;
                triangle.Vertex3 = v3;

                triangle.Index1 = index1;
                triangle.Index2 = index2;
                triangle.Index3 = index3;

                Triangles[i / 3] = triangle;
            }
        }
    }
}
